package com.txsj.scan.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.greendao.EpcInfoDao;
import com.greendao.GoodsInfoDao;
import com.txsj.scan.R;
import com.txsj.scan.adapter.InventoryAdapter;
import com.txsj.scan.base.BaseActivity;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.InventoryBatchBean;
import com.txsj.scan.bean.InventoryChangeBean;
import com.txsj.scan.bean.InventoryIdBean;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.fragment.SelectGoodsListFragment;
import com.txsj.scan.presenter.InventoryPresenter;
import com.txsj.scan.utils.GsonFactory;
import com.txsj.scan.view.IInventoryView;
import com.txsj.scan.widget.TSnackbarView;
import com.txsj.scan.widget.TitleBarView;
import com.txsj.scan.widget.dialog.CustomDialog;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by wangchuangjun on 2018/11/13
 * Desc: 盘点
 */

public class InventoryActivity extends BaseActivity<InventoryPresenter> implements IInventoryView {

    public static final int REQUEST_CHOOSE_GOODS = 0x186;
    private RecyclerView recyclerView;
    private TitleBarView mTitle;
    private TextView tv_out_name,tv_inventory_count,tv_system_count,tv_profit_loss_count;
    private EditText et_remarks;
    private InventoryAdapter adapter;
    int allCount,systemCount;

    private WarehouseBean warehouseBean;
    private List<InventoryBatchBean> commitBatchBeanList;//盘点选中的批次列表
    private int changePosition = -1;//点击商品之后记录点击的商品位置

    private List<InventoryChangeBean> changeList;//盘点最终要提交的集合
    private List<EpcInfo> epcInfoList;//查询本地数据库得到的标签集合
    private List<InventoryIdBean> idList;





    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inventory);


        initView();
        initData();
    }

    private void initData() {
        commitBatchBeanList = new ArrayList<>();
        changeList = new ArrayList<>();
        epcInfoList = new ArrayList<>();
        idList = new ArrayList<>();
        String jsonaArray0 = getIntent().getStringExtra("warehouse");
        warehouseBean = new Gson().fromJson(jsonaArray0,WarehouseBean.class);
        if (null != warehouseBean && !TextUtils.isEmpty(warehouseBean.getWarehouse_name())) {
            tv_out_name.setText(warehouseBean.getWarehouse_name());
        }
        String jsonaArray = getIntent().getStringExtra("data");
        if (TextUtils.isEmpty(jsonaArray)){
            return;
        }
        List<GoodsInfo> epcGoodsInfoList = GsonFactory.getObjectList(jsonaArray,GoodsInfo.class);
        if (null != epcGoodsInfoList && epcGoodsInfoList.size() > 0) {
            for (GoodsInfo goodsInfo:epcGoodsInfoList){
                goodsInfo.setCount(goodsInfo.getEpcList().size());
            }
            adapter.setData(epcGoodsInfoList);
        }

        refreshShow();

        setData();
    }

    private void initView() {
        this.mTitle = (TitleBarView) findViewById(R.id.mTitle);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        tv_out_name = (TextView) findViewById(R.id.tv_out_name);
        tv_system_count = (TextView) findViewById(R.id.tv_system_count);
        tv_profit_loss_count = (TextView) findViewById(R.id.tv_profit_loss_count);
        tv_inventory_count = (TextView) findViewById(R.id.tv_inventory_count);
        et_remarks = (EditText) findViewById(R.id.et_remarks);
        this.mTitle.setRightOnclickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isRepeatClick())return;
                //如果提交的数量<系统数量，那么可能扫不全，进行提示
                if (getCommitListCount() < systemCount) {
                    final CustomDialog dialog = new CustomDialog(InventoryActivity.this);
                    dialog.setTitleStr("盘点提示？");
                    String steTip = "盘存数量（" + getCommitListCount() + "）与当前仓库可用\n" +
                            "标签数量（" + systemCount + "）存在差异，请检\n" +
                            "查是否有未读到的商品；\n" +
                            "\n" +
                            "继续盘点请认真核对商品数量！";
                    dialog.setContent(steTip);
                    dialog.setCancelVisiable();
                    dialog.setOkVisiable("盘点", new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            dialog.dismiss();
                            toCommitInventory();
                        }
                    });
                    dialog.show();
                }else {
                    toCommitInventory();
                }
            }
        });
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new InventoryAdapter(this);
        recyclerView.setAdapter(adapter);
        adapter.setListener(new InventoryAdapter.OnItemClickListener() {
            @Override
            public void onDelete(int position) {
                //TODO 删除列表中的数据
                removeData(adapter.getList().get(position));
                adapter.removeData(position);
                refreshShow();
            }

            @Override
            public void onItemClick(int pisition) {
                Intent intent = new Intent(InventoryActivity.this, InventoryBatchActivity.class);
                intent.putExtra("data",new Gson().toJson(adapter.getInventoryBean(pisition)));
                intent.putExtra("from",InventoryActivity.class.getSimpleName());
                intent.putExtra("warehouse",new Gson().toJson(warehouseBean));
                intent.putExtra("type","0");
                startActivityForResult(intent,REQUEST_CHOOSE_GOODS);
                changePosition = pisition;
            }
        });
    }

    /**
     * 在进行提交盘存的时候判断提交的数量<系统库存数量的时候提示文字
     * @return
     */
    private int getCommitListCount() {
        int count = 0;
        for (GoodsInfo info:adapter.getList()){
            count += info.getCount();
        }
        return count;
    }

    /**
     * 当list中的集合被删掉后，提交列表中的数据也要从中去除掉
     * 1. 首先通过epcGoodsInfo对象获取strEpc标签
     * 2. 再通过epclist集合查询标签库对应的标签
     * 3. 再通过标签信息中的batch_id对比idList，成功后
     * 4.
     * @param epcGoodsInfo
     */
    private void removeData(GoodsInfo epcGoodsInfo) {

        List<EpcInfo> epcList = epcGoodsInfo.getEpcList();
        if (null != epcList && epcList.size() > 0) {
            for (EpcInfo strEpc : epcList) {
                String epcCode = strEpc.getStrEpc().substring(9, strEpc.getStrEpc().length());
                long id = Long.parseLong(epcCode, 16);
                List<EpcInfo> listss = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().queryBuilder()
                        .where(EpcInfoDao.Properties.Tag_id.eq(id))
                        .list();
                if (null != listss && listss.size() > 0) {
                    for (InventoryIdBean idBean :idList){
                        if (idBean.getBatch_id() == listss.get(0).getBatch_id()){
                            boolean isContain = false;
                            int position = -1;
                            for (int i = 0;i<changeList.size(); i++){
                                if (changeList.get(i).getInventory_id() == idBean.getInventory_id()){
                                    isContain = true;
                                    position = i;
                                    break;
                                }
                            }
                            if (isContain){
                                changeList.remove(position);
                                break;
                            }
                        }
                    }
                }
            }
        }
    }

    /**
     * 提交盘点的数据
     */
    private void toCommitInventory() {
        if (changeList.size() == 0){
            showErrorMsg("没有可提交的数据");
            return;
        }
        presenter.getCommitChangeList(changeList,warehouseBean,TextUtils.isEmpty(et_remarks.getText().toString())?"无":et_remarks.getText().toString());
    }


    @Override
    protected InventoryPresenter providePresenter() {
        return presenter = new InventoryPresenter(this);
    }

    @Override
    public Context context() {
        return this;
    }

    /**
     * 扫条码
     * @param view
     */
    public void clickScanCode(View view) {
        presenter.fromCodeGetGoodsData("4891028706656");
    }
    /**
     * 选商品
     * @param view
     */
    public void clickChooseGoods(View view) {
        Intent intent = new Intent(this,GoodsListActivity.class);
        intent.putExtra("data",new Gson().toJson(warehouseBean));
        startActivityForResult(intent,REQUEST_CHOOSE_GOODS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (null == data || null == data.getStringExtra("data"))return;
        if (requestCode == REQUEST_CHOOSE_GOODS && resultCode == SelectGoodsListFragment.RESULT_COMMIT_BATCH_CODE){
            String json = data.getStringExtra("data");
            List<InventoryBatchBean> list = GsonFactory.getObjectList(json,InventoryBatchBean.class);

            //返回之后进行数据合并
            combineCommitData(list);
        }else if(requestCode == REQUEST_CHOOSE_GOODS && resultCode == InventoryBatchActivity.RESULT_COMMIT_BATC_CODE){
            String json = data.getStringExtra("data");
            List<InventoryBatchBean> list = GsonFactory.getObjectList(json,InventoryBatchBean.class);
            String goodsInfoJson = data.getStringExtra("goods_info");
            GoodsInfo goodsInfo = new Gson().fromJson(goodsInfoJson, GoodsInfo.class);

            long count= 0;
            for (InventoryBatchBean bean:list){
                count += bean.getChange_num();
            }
            adapter.updateData(changePosition,count);

            //返回之后进行数据合并
            combineCommitData(list);
        } else if (requestCode == REQUEST_CHOOSE_GOODS && resultCode == InventoryBatchActivity.RESULT_SCAN_BATC_CODE) {
            String json = data.getStringExtra("data");
            List<InventoryBatchBean> list = GsonFactory.getObjectList(json,InventoryBatchBean.class);

            //返回之后进行数据合并
            combineCommitData(list);
        }
    }


    /**
     * 将返回的数据主要有商品列表页和批次列表页返回的
     */
    private void combineCommitData(List<InventoryBatchBean> list) {
        //对当前返回的数据进行合并
        for (InventoryBatchBean bean:list){
            boolean isContains = false;
            for (int i = 0;i<commitBatchBeanList.size();i++){
                if (bean.getBatch_id() == commitBatchBeanList.get(i).getBatch_id()){
                    isContains = true;
                    commitBatchBeanList.get(i).setChange_num(bean.getChange_num());
                    commitBatchBeanList.get(i).setGoods_count(bean.getGoods_count());
                    commitBatchBeanList.get(i).setInventory_keep(bean.getInventory_keep());
                    break;
                }
            }
            if (!isContains){
                commitBatchBeanList.add(bean);
            }
        }


        /**
         * 合并完成后进行提交数据类型封装
         * 封装之前先判断一下提交的列表里是否存在该库存id
         */

        for (InventoryBatchBean inventoryBatchBean:commitBatchBeanList){
            boolean isContain = false;
            for (InventoryChangeBean changeBean:changeList) {
                if (changeBean.getInventory_id() == inventoryBatchBean.getInventory_id()) {
                    changeBean.setGoods_count(inventoryBatchBean.getGoods_count());
                    isContain = true;
                    break;
                }
            }
            if (!isContain){
                InventoryChangeBean changeBean = new InventoryChangeBean();
                changeBean.setInventory_id(inventoryBatchBean.getInventory_id());
                changeBean.setGoods_count(inventoryBatchBean.getGoods_count());
                changeList.add(changeBean);
            }
        }

        refreshShow();
    }

    /**
     * 刷新展示状态
     */
    private void refreshShow() {
        /**
         * 盘点数量改变后显示问题
         */
        allCount = 0;
        for (GoodsInfo epcGoodsInfo:adapter.getList()){
            allCount+=epcGoodsInfo.getCount();
        }
        tv_inventory_count.setText(allCount+"");

        List<GoodsInfo> list = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder().
                where(GoodsInfoDao.Properties.Warehouse_id.eq(warehouseBean.getWarehouse_id()))
                .list();
        systemCount = 0;//系统商品数量
        float all_profit_loss_price = 0.0f;//所有盈亏金额
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        for (GoodsInfo goodsInfo:list){
            for (GoodsInfo epcGoodsInfo :adapter.getList()){
                if (goodsInfo.getGoods_id() == epcGoodsInfo.getGoods_id()){
                    epcGoodsInfo.setUnit_price(goodsInfo.getUnit_price());
                    epcGoodsInfo.setInventory_keep(goodsInfo.getInventory_keep());
                    adapter.updateData(epcGoodsInfo);

                    systemCount += goodsInfo.getInventory_keep();
                    //盈亏数量
                    long profit_loss_count = epcGoodsInfo.getCount() - epcGoodsInfo.getInventory_keep();
                    //盈亏金额
                    float profit_loss_price = profit_loss_count * Float.valueOf(decimalFormat.format(goodsInfo.getUnit_price()));
                    //盈亏总和
                    all_profit_loss_price +=profit_loss_price;
                }
            }
        }

        tv_profit_loss_count.setText(decimalFormat.format(all_profit_loss_price));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        presenter.onDestroy();
    }

    @Override
    public void onLoading() {
        showLoading();
    }

    @Override
    public void onSuccess(String msg) {
        hideLoading();
        setData();
    }

    /**
     * 通过扫描到的商品信息进行商品统计
     */
    private void setData() {
        List<GoodsInfo> list = GreenDaoUtils.getSingleTon().getmDaoSession().getGoodsInfoDao().queryBuilder().
                where(GoodsInfoDao.Properties.Warehouse_id.eq(warehouseBean.getWarehouse_id()))
                .list();
        systemCount = 0;//系统商品数量
        float all_profit_loss_price = 0.0f;//所有盈亏金额
        DecimalFormat decimalFormat = new DecimalFormat("0.00");
        for (GoodsInfo goodsInfo:list){
            for (GoodsInfo epcGoodsInfo :adapter.getList()){
                if (goodsInfo.getGoods_id() == epcGoodsInfo.getGoods_id()){
                    epcGoodsInfo.setUnit_price(goodsInfo.getUnit_price());
                    epcGoodsInfo.setInventory_keep(goodsInfo.getInventory_keep());
                    adapter.updateData(epcGoodsInfo);

                    systemCount += goodsInfo.getInventory_keep();
                    //盈亏数量
                    long profit_loss_count = epcGoodsInfo.getCount() - epcGoodsInfo.getInventory_keep();
                    //盈亏金额
                    float profit_loss_price = profit_loss_count * Float.valueOf(decimalFormat.format(goodsInfo.getUnit_price()));
                    //盈亏总和
                    all_profit_loss_price +=profit_loss_price;
                }
            }
        }
        tv_system_count.setText(systemCount+"");
        tv_profit_loss_count.setText(decimalFormat.format(all_profit_loss_price));

        //重新将本地扫描到的数据转化成InventoryBatchBean类的集合，准备添加
        //通过传过来的strEPC来判断是哪个批次信息
        epcInfoList = new ArrayList<>();
        for (GoodsInfo epcGoodsInfo:adapter.getList()) {
            List<EpcInfo> epcList = epcGoodsInfo.getEpcList();
            if (null != epcList && epcList.size() > 0) {
                for (EpcInfo strEpc : epcList) {
                    String epcCode = strEpc.getStrEpc().substring(9, strEpc.getStrEpc().length());
                    long id = Long.parseLong(epcCode, 16);
                    List<EpcInfo> listss = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().queryBuilder()
                            .where(EpcInfoDao.Properties.Tag_id.eq(id))
                            .list();
                    if (null != listss && listss.size() > 0) {
                        epcInfoList.add(listss.get(0));
                    }
                }
            }
        }

        presenter.getScanInventoryIdList(epcInfoList,warehouseBean.getWarehouse_id()+"");
    }

    @Override
    public void onError(String msg) {
        showErrorMsg(msg);
        hideLoading();
    }

    @Override
    public void onInventoryIdEmpty(String msg) {
        hideLoading();
        showErrorMsg(msg);
    }

    @Override
    public void onInventoryIdError(String msg) {
        hideLoading();
        showErrorMsg(msg);

    }

    @Override
    public void onInventoryIdSuccess(List<InventoryIdBean> list) {
        hideLoading();
        idList = list;//当前记录一下，在删除数据的时候要用到

        //创建一个临时的tempList集合，合并批次号相同的批次信息，并使count++
        List<EpcInfo> tempList = new ArrayList<>();
        for (EpcInfo epcInfo:epcInfoList){
            epcInfo.setEpcCount(1);
            boolean isContain = false;
            for (int i = 0; i < tempList.size(); i++) {
                if(epcInfo.getBatch_id() == tempList.get(i).getBatch_id()){
                    int count = tempList.get(i).getEpcCount();
                    tempList.get(i).setEpcCount(++count);
                    isContain = true;
                }
            }
            if (!isContain){
                tempList.add(epcInfo);
            }
        }

        //循环遍历合并完的templist集合，将数据塞进可用于提交的changlist集合中
        for (EpcInfo tempEpcInfo:tempList){
            for (InventoryIdBean bean:list){
                if (tempEpcInfo.getBatch_id() == bean.getBatch_id()){
                    InventoryChangeBean changeBean = new InventoryChangeBean();
                    changeBean.setGoods_count(tempEpcInfo.getEpcCount()-bean.getInventory_keep());
                    changeBean.setInventory_id(bean.getInventory_id());
                    changeList.add(changeBean);
                }
            }
        }
    }

    @Override
    public void onCommitSuccess() {
        hideLoading();
        showErrorMsg("盘点成功");
        Intent intent = new Intent(this, SelectGoodsListActivity.class);
        intent.putExtra("from",InventoryActivity.class.getSimpleName());
        startActivity(intent);
    }

    @Override
    public void onCommitError(String msg) {
        hideLoading();
        showErrorMsg(msg);
    }

    @Override
    public void showErrorMsg(String msg) {
        new TSnackbarView(this.mTitle, msg);
    }

    @Override
    public void getGoodsData(GoodsInfo mGoods) {
        Intent intent = new Intent(InventoryActivity.this, InventoryBatchActivity.class);
        intent.putExtra("data", new Gson().toJson(mGoods));
        intent.putExtra("warehouse", new Gson().toJson(warehouseBean));
        intent.putExtra("from", "InventoryActivity");
        intent.putExtra("type", "4");
        startActivityForResult(intent, REQUEST_CHOOSE_GOODS);
    }

}
